package com.csii.user.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.csii.core.api.Result;
import com.csii.core.system.vo.LoginUser;
import com.csii.core.util.oConvertUtils;
import com.csii.user.entity.SysUser;
import com.csii.user.service.ISysDepartService;
import com.csii.user.service.ISysUserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * @Author ian
 * @since 2018-12-17
 */
@RestController
@RequestMapping("/sys")
@Api(tags="用户登录")
@Slf4j
public class LoginController {
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysDepartService sysDepartService;
	/**
	 * 登陆成功选择用户当前部门
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/selectDepart", method = RequestMethod.PUT)
	public Result<JSONObject> selectDepart(@RequestBody SysUser user) {
		Result<JSONObject> result = new Result<JSONObject>();
		String username = user.getUsername();
		LoginUser loginUser = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(oConvertUtils.isEmpty(username)) {
			username = loginUser.getUsername();
		}
		String orgCode= user.getOrgCode();
		this.sysUserService.updateUserDepart(username, orgCode);
		//清除用戶緩存
		sysUserService.valiUserCahce(username);
		JSONObject obj = new JSONObject();
		loginUser.setOrgCode(orgCode);
		obj.put("userInfo", loginUser);
		obj.put("departInfo",sysDepartService.getSysDepartByCode(orgCode));
		result.setResult(obj);
		return result;
	}
	/**
	 * 获取用户当前部门
	 * @return
	 */
	@RequestMapping(value = "/getDepart", method = RequestMethod.GET)
	public Result<JSONObject> getDepart() {
		Result<JSONObject> result = new Result<JSONObject>();
		LoginUser loginUser = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String orgCode=sysUserService.getUserByName(loginUser.getUsername()).getOrgCode();
		JSONObject obj = new JSONObject();
		obj.put("departInfo", StrUtil.isEmpty(orgCode)?"":sysDepartService.getSysDepartByCode(orgCode));
		result.setResult(obj);
		return result;
	}
}
